package info.wangyuan.agent.controller.admin;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import info.wangyuan.agent.entity.po.FileInfo;
import info.wangyuan.agent.service.curd.FileInfoService;
import info.wangyuan.agent.utils.Result;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

import java.util.List;

/**
 * 知识库文件管理
 *
 * @author Albert
 * @since 2025-07-15 21:43:07
 */
@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/admin/file")
public class FileInfoController {

    private final FileInfoService fileInfoService;

    public FileInfoController(FileInfoService fileInfoService) {
        this.fileInfoService = fileInfoService;
    }

    /**
     * 获取知识库文件列表
     */
    @GetMapping("/list/{knowledgeBaseId}")
    public Result<List<FileInfo>> getFileInfoList(@PathVariable @NotNull Integer knowledgeBaseId) {
        return Result.success(fileInfoService.list(Wrappers.lambdaQuery(FileInfo.class)
                .eq(FileInfo::getKnowledgeBaseId, knowledgeBaseId)));
    }

    /**
     * 知识库文件批量上传
     */
    @PostMapping("/add")
    public Result<Void> addFileInfo(@RequestParam List<MultipartFile> files,
                                    @RequestParam @NotNull Integer kbId) {
        fileInfoService.saveFile(files, kbId);
        return Result.success();
    }

    /**
     * 知识库文件修改
     */
    @PostMapping("/update")
    public Result<Void> updateFileInfo(@RequestBody @Valid FileInfo fileInfo) {
        fileInfoService.canUpdate(fileInfo);
        return Result.success();
    }

    /**
     * 知识库文件删除
     */
    @DeleteMapping("/delete/{id}")
    public Result<Void> deleteFileInfo(@PathVariable @NotNull Integer id) {
        fileInfoService.canDelete(id);
        return Result.success();
    }

    /**
     * 知识库文件下载
     */
    @GetMapping("/download/{id}")
    public Result<ResponseEntity<StreamingResponseBody>> downloadFileInfo(@PathVariable @NotNull Integer id) {
        return Result.success(fileInfoService.downloadFile(id));
    }

}
